/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tools;

import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Geometry;
import com.jme3.scene.Spatial;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;
import com.jme3.util.BufferUtils;
import java.nio.Buffer;

/**
 *
 * @author Jannes
 */
public class CrossSectionControl extends AbstractControl{        
    
    private Vector3f camLocation, spatialLocation;
    private static Buffer[] buffers = null;
    private static int FRONT = 0;
    private static int BACK = 1;
    private int currentRelPos;
    
    
    public CrossSectionControl(){
        super();
        currentRelPos = FRONT;
        if(buffers == null){
            buffers = new Buffer[2];            
            int[] indexes0 = {22,20,21,21,23,22, 18,17,16,17,18,19, 10,9,8,9,10,11, 14,12,13,13,15,14, 6,5,4,5,6,7, 2,0,1,1,3,2};
            buffers[0] = BufferUtils.createIntBuffer(indexes0);
            int[] indexes1 = { 6,5,4,5,6,7, 2,0,1,1,3,2, 30,29,28,29,30,31, 26,24,25,25,27,26, 22,20,21,21,23,22, 18,17,16,17,18,19};
            buffers[1] = BufferUtils.createIntBuffer(indexes1);
        }        
    }
    
    @Override
    protected void controlUpdate(float tpf) {        
    }

    /* relativePosition:
     *  1 | 0      
     * ---s---
     *  3 | 2                
     */
    
    @Override
    protected void controlRender(RenderManager rm, ViewPort vp) {
        Camera cam = vp.getCamera();
        camLocation = cam.getLocation();        
        spatialLocation = spatial.getWorldTranslation();        
        int newRelPos = FRONT;
        if(camLocation.z < spatialLocation.z){
            newRelPos = BACK;
        }        
        if(newRelPos != currentRelPos){            
            currentRelPos = newRelPos;
            ((Geometry)spatial).getMesh().getBuffer(Type.Index).updateData(
                        buffers[currentRelPos]);                               
        }                
    }

    public Control cloneForSpatial(Spatial spatial) {
        CrossSectionControl control = new CrossSectionControl();
        control.currentRelPos = this.currentRelPos;
        control.setSpatial(spatial);
        return control;       
    }
    
}
